import 'package:FlutterStudy/iconStudy.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class DialogDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('Dialog 使用示例'), backgroundColor: Colors.blue),
      body: Builder(
        builder: (BuildContext scaffoldContext) {
          return ListView(
            padding: EdgeInsets.all(16),
            children: [
              _buildDialogButton(
                context,
                'Simple Dialog',
                Icons.message,
                    () => _showSimpleDialog(context),
              ),
              _buildDialogButton(
                context,
                'AlertDialog',
                Icons.warning,
                    () => _showAlertDialog(context),
              ),
              _buildDialogButton(
                context,
                'Custom AlertDialog',
                Icons.design_services,
                    () => _showCustomAlertDialog(context),
              ),
              _buildDialogButton(
                context,
                'Confirmation Dialog',
                Icons.help,
                    () => _showConfirmationDialog(context),
              ),
              _buildDialogButton(
                context,
                'Single Choice Dialog',
                Icons.radio_button_checked,
                    () => _showSingleChoiceDialog(context),
              ),
              _buildDialogButton(
                context,
                'Multi Choice Dialog',
                Icons.check_box,
                    () => _showMultiChoiceDialog(context),
              ),
              _buildDialogButton(
                context,
                'TextInput Dialog',
                Icons.text_fields,
                    () => _showTextInputDialog(context),
              ),
              _buildDialogButton(
                context,
                'DatePicker Dialog',
                Icons.calendar_today,
                    () => _showDatePickerDialog(context),
              ),
              _buildDialogButton(
                context,
                'TimePicker Dialog',
                Icons.access_time,
                    () => _showTimePickerDialog(context),
              ),
              _buildDialogButton(
                context,
                'Bottom Sheet',
                Icons.vertical_align_bottom,
                    () => _showBottomSheet(scaffoldContext),
              ),
              _buildDialogButton(
                context,
                'Modal Bottom Sheet',
                Icons.vertical_align_bottom_outlined,
                    () => _showModalBottomSheet(context),
              ),
              _buildDialogButton(
                context,
                'Custom Dialog',
                Icons.widgets,
                    () => _showCustomDialog(context),
              ),
              _buildDialogButton(
                context,
                'Loading Dialog',
                Icons.hourglass_bottom,
                    () => _showLoadingDialog(context),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildDialogButton(BuildContext context,
      String title,
      IconData icon,
      VoidCallback onTap,) {
    return Card(
      margin: EdgeInsets.symmetric(vertical: 8),
      child: ListTile(
        leading: Icon(icon, size: 30, color: Colors.blue),
        title: Text(title, style: TextStyle(fontSize: 18)),
        trailing: Icon(Icons.arrow_forward_ios),
        onTap: onTap,
      ),
    );
  }

  // 1. Simple Dialog
  void _showSimpleDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: Text('选择一个选项'),
          children: [
            SimpleDialogOption(
              onPressed: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(
                  context,
                ).showSnackBar(SnackBar(content: Text('选择了选项 A')));
              },
              child: Row(
                children: [
                  Icon(Icons.account_circle, color: Colors.blue),
                  Padding(
                    padding: EdgeInsets.only(left: 16),
                    child: Text('选项 A'),
                  ),
                ],
              ),
            ),
            SimpleDialogOption(
              onPressed: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(
                  context,
                ).showSnackBar(SnackBar(content: Text('选择了选项 B')));
              },
              child: Row(
                children: [
                  Icon(Icons.settings, color: Colors.green),
                  Padding(
                    padding: EdgeInsets.only(left: 16),
                    child: Text('选项 B'),
                  ),
                ],
              ),
            ),
            SimpleDialogOption(
              onPressed: () => Navigator.pop(context),
              child: Row(
                children: [
                  Icon(Icons.cancel, color: Colors.red),
                  Padding(
                    padding: EdgeInsets.only(left: 16),
                    child: Text('取消'),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  // 2. AlertDialog
  void _showAlertDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('提示'),
          content: Text('这是一个标准的 AlertDialog'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(
                  context,
                ).showSnackBar(SnackBar(content: Text('确认操作')));
              },
              child: Text('确认'),
            ),
          ],
        );
      },
    );
  }

  // 3. Custom AlertDialog
  Future<void> _showCustomAlertDialog(BuildContext context) async {
    int dialogResult = await showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(55),
          ),
          title: Row(
            children: [
              Icon(Icons.warning, color: Colors.orange, size: 28),
              SizedBox(width: 10),
              Text('警告'),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('您的操作将会删除所有数据，确定要继续吗？'),
              SizedBox(height: 15),
              Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.orange.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color: Colors.orange.withOpacity(0.3)),
                ),
                child: Text(
                  '注意：此操作不可撤销！',
                  style: TextStyle(color: Colors.orange, fontSize: 12),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, 1),
              child: Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context, 0);
                ScaffoldMessenger.of(
                  context,
                ).showSnackBar(SnackBar(content: Text('已删除所有数据')));
              },
              style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
              child: Text('删除', style: TextStyle(color: Colors.white)),
            ),
          ],
        );
      },
    );
    print("dialog的结果 ${dialogResult}");
  }

  // 4. Confirmation Dialog
  Future<void> _showConfirmationDialog(BuildContext context) async {
    bool? result = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('确认操作'),
          content: Text('您确定要执行此操作吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, false),
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.pop(context, true),
              child: Text('确定'),
            ),
          ],
        );
      },
    );

    if (result == true) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('操作已确认')));
    }
  }

  // 5. Single Choice Dialog
  void _showSingleChoiceDialog(BuildContext context) {
    int selectedValue = 0;
    final List<String> options = ['选项 1', '选项 2', '选项 3', '选项 4'];

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('单选对话框'),
          content: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: List.generate(options.length, (index) {
                  return RadioListTile<int>(
                    title: Text(options[index]),
                    value: index,
                    groupValue: selectedValue,
                    onChanged: (int? value) {
                      setState(() {
                        selectedValue = value!;
                      });
                    },
                  );
                }),
              );
            },
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('选择了: ${options[selectedValue]}')),
                );
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }

  // 6. Multi Choice Dialog
  void _showMultiChoiceDialog(BuildContext context) {
    List<bool> selectedValues = List.generate(5, (index) => false);
    final List<String> options = [
      '选项 A',
      '选项 B',
      '选项 C',
      '选项 D',
      '选项 E'
    ];

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('多选对话框'),
          content: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Container(
                width: double.maxFinite,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: List.generate(options.length, (index) {
                    return CheckboxListTile(
                      title: Text(options[index]),
                      value: selectedValues[index],
                      onChanged: (bool? value) {
                        setState(() {
                          selectedValues[index] = value!;
                        });
                      },
                    );
                  }),
                ),
              );
            },
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                List<String> selected = [];
                for (int i = 0; i < selectedValues.length; i++) {
                  if (selectedValues[i]) {
                    selected.add(options[i]);
                  }
                }
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('选择了: ${selected.join(', ')}')),
                );
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }

  // 7. TextInput Dialog
  void _showTextInputDialog(BuildContext context) {
    TextEditingController _controller = TextEditingController();

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('输入文本'),
          content: TextField(
            controller: _controller,
            decoration: InputDecoration(
              hintText: "请输入内容",
              border: OutlineInputBorder(),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                if (_controller.text.isNotEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('输入的内容: ${_controller.text}')),
                  );
                }
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }

  // 8. DatePicker Dialog
  void _showDatePickerDialog(BuildContext context) async {
    DateTime? pickedDate = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.light(
              primary: Colors.blue,
              onPrimary: Colors.white,
              surface: Colors.white,
              onSurface: Colors.black,
            ),
            textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(foregroundColor: Colors.blue),
            ),
          ),
          child: child!,
        );
      },
    );

    if (pickedDate != null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            '选择的日期: ${pickedDate.year}-${pickedDate.month}-${pickedDate
                .day}',
          ),
        ),
      );
    }
  }

  // 9. TimePicker Dialog
  void _showTimePickerDialog(BuildContext context) async {
    TimeOfDay? pickedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
      builder: (BuildContext context, Widget? child) {
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
          child: child!,
        );
      },
    );

    if (pickedTime != null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择的时间: ${pickedTime.format(context)}')),
      );
    }
  }

  // 10. Bottom Sheet
  void _showBottomSheet(BuildContext context) {
    Scaffold.of(context).showBottomSheet((context) {
      return Container(
        height: 200,
        width: 600,
        color: Colors.white,
        child: Column(
          children: [
            Text('非模态底部工作表'),
            ElevatedButton(
              onPressed: () {
                // 可以在这里操作主界面内容
                Navigator.pop(context);
              },
              child: Text('关闭'),
            ),
          ],
        ),
      );
    });
  }

  // 11. Modal Bottom Sheet
  void _showModalBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (BuildContext context) {
        return Container(
          height: 400,
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.all(10),
                width: 40,
                height: 5,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(5),
                ),
              ),
              Padding(
                padding: EdgeInsets.all(16),
                child: Text(
                  '选择操作',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
              ),
              Divider(),
              ListTile(
                leading: Icon(Icons.photo, color: Colors.blue),
                title: Text('从相册选择'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(SnackBar(content: Text('从相册选择')));
                },
              ),
              ListTile(
                leading: Icon(Icons.camera_alt, color: Colors.green),
                title: Text('拍照'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(SnackBar(content: Text('拍照')));
                },
              ),
              ListTile(
                leading: Icon(Icons.file_upload, color: Colors.orange),
                title: Text('上传文件'),
                onTap: () {
                  Navigator.pop(context);
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(SnackBar(content: Text('上传文件')));
                },
              ),
              Spacer(),
              Container(
                width: double.infinity,
                margin: EdgeInsets.all(16),
                child: ElevatedButton(
                  onPressed: () => Navigator.pop(context),
                  child: Text('取消'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey[200],
                    foregroundColor: Colors.black,
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 12. Custom Dialog
  void _showCustomDialog(BuildContext context) {
    // 设置状态栏透明，让内容可以延伸到状态栏区域

    showDialog(
        context: context,
        barrierDismissible: false, // 用户不能点击外部关闭
        useSafeArea: false,
        barrierColor:Colors.amber,
        builder: (BuildContext context)
    {
      return Dialog.fullscreen(
        backgroundColor: Colors.green,
        child: Center(
          child: Stack(
            children: [
              Container(
                padding: EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: Colors.pink,
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black26,
                      blurRadius: 10,
                      offset: Offset(0, 10),
                    ),
                  ],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    CircleAvatar(
                      radius: 40,
                      backgroundColor: Colors.blue.withOpacity(0.2),
                      child: Icon(
                          Icons.check, color: Colors.blue, size: 40),
                    ),
                    SizedBox(height: 20),
                    Text(
                      '操作成功',
                      style: TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 10),
                    Text(
                      '您的操作已经成功完成',
                      style: TextStyle(
                          fontSize: 16, color: Colors.grey[600]),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(height: 30),
                    ElevatedButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text(
                        '确定',
                        style: TextStyle(color: Colors.white),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        minimumSize: Size(150, 45),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
      // return Dialog(
      //   shape: RoundedRectangleBorder(
      //     borderRadius: BorderRadius.circular(20),
      //   ),
      //   elevation: 0,
      //   insetPadding: EdgeInsets.only(top: 100),
      //   backgroundColor: Colors.amber,
      //   child: Center(
      //     child: Stack(
      //       children: [
      //         Container(
      //           padding: EdgeInsets.all(20),
      //           decoration: BoxDecoration(
      //             color: Colors.white,
      //             shape: BoxShape.rectangle,
      //             borderRadius: BorderRadius.circular(20),
      //             boxShadow: [
      //               BoxShadow(
      //                 color: Colors.black26,
      //                 blurRadius: 10,
      //                 offset: Offset(0, 10),
      //               ),
      //             ],
      //           ),
      //           child: Column(
      //             mainAxisSize: MainAxisSize.min,
      //             children: [
      //               CircleAvatar(
      //                 radius: 40,
      //                 backgroundColor: Colors.blue.withOpacity(0.2),
      //                 child: Icon(Icons.check, color: Colors.blue, size: 40),
      //               ),
      //               SizedBox(height: 20),
      //               Text(
      //                 '操作成功',
      //                 style: TextStyle(
      //                   fontSize: 24,
      //                   fontWeight: FontWeight.bold,
      //                 ),
      //               ),
      //               SizedBox(height: 10),
      //               Text(
      //                 '您的操作已经成功完成',
      //                 style: TextStyle(fontSize: 16, color: Colors.grey[600]),
      //                 textAlign: TextAlign.center,
      //               ),
      //               SizedBox(height: 30),
      //               ElevatedButton(
      //                 onPressed: () => Navigator.pop(context),
      //                 child: Text(
      //                   '确定',
      //                   style: TextStyle(color: Colors.white),
      //                 ),
      //                 style: ElevatedButton.styleFrom(
      //                   backgroundColor: Colors.blue,
      //                   minimumSize: Size(150, 45),
      //                   shape: RoundedRectangleBorder(
      //                     borderRadius: BorderRadius.circular(30),
      //                   ),
      //                 ),
      //               ),
      //             ],
      //           ),
      //         ),
      //       ],
      //     ),
      //   ),
      // );
    },);
  }

  void _showCustomDialog1(BuildContext context) {
    // 设置状态栏透明，让内容可以延伸到状态栏区域
    if (Theme
        .of(context)
        .platform == TargetPlatform.android) {
      // android 平台
      SystemUiOverlayStyle _style = SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        systemStatusBarContrastEnforced: false,
      );
      SystemChrome.setSystemUIOverlayStyle(_style);
    }

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return Dialog.fullscreen(
          backgroundColor: Colors.white,
          child: Stack(
            children: [
              // 主要内容 - 使用 MediaQuery.removePadding 移除安全区域
              Positioned.fill(
                child: MediaQuery.removePadding(
                  context: context,
                  removeTop: true, // 移除顶部安全区域
                  child: SingleChildScrollView(
                    padding: EdgeInsets.zero,
                    child: Column(
                      children: [
                        // 顶部内容区域（延伸到状态栏）
                        Container(
                          height: 100 + MediaQuery
                              .of(context)
                              .padding
                              .top,
                          width: double.infinity,
                          color: Colors.blue,
                          child: Stack(
                            children: [
                              // 状态栏区域内容
                              Positioned(
                                top: MediaQuery
                                    .of(context)
                                    .padding
                                    .top,
                                left: 0,
                                right: 0,
                                child: Center(
                                  child: Text(
                                    '标题',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 20,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        // 其他内容
                        Container(
                          padding: EdgeInsets.all(20),
                          child: Column(
                            children: [
                              CircleAvatar(
                                radius: 40,
                                backgroundColor: Colors.blue.withOpacity(0.2),
                                child: Icon(
                                    Icons.check, color: Colors.blue, size: 40),
                              ),
                              SizedBox(height: 20),
                              Text(
                                '操作成功',
                                style: TextStyle(
                                  fontSize: 24,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              SizedBox(height: 10),
                              Text(
                                '您的操作已经成功完成',
                                style: TextStyle(
                                    fontSize: 16, color: Colors.grey[600]),
                                textAlign: TextAlign.center,
                              ),
                              SizedBox(height: 30),
                              ElevatedButton(
                                onPressed: () => Navigator.pop(context),
                                child: Text(
                                  '确定',
                                  style: TextStyle(color: Colors.white),
                                ),
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Colors.blue,
                                  minimumSize: Size(150, 45),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(30),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              // 关闭按钮
              Positioned(
                right: 16,
                top: MediaQuery
                    .of(context)
                    .padding
                    .top + 16,
                child: IconButton(
                  icon: Icon(Icons.close, color: Colors.grey),
                  onPressed: () => Navigator.pop(context),
                ),
              ),
            ],
          ),
        );
      },
    ).then((_) {
      // 恢复状态栏样式
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarColor: Colors.blue, // 恢复原来的状态栏颜色
        statusBarIconBrightness: Brightness.light,
      ));
    });
  }

  // 13. Loading Dialog
  void _showLoadingDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Container(
            padding: EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                ),
                SizedBox(height: 20),
                Text('加载中...', style: TextStyle(fontSize: 16)),
              ],
            ),
          ),
        );
      },
    );

    // 模拟加载3秒后自动关闭
    Future.delayed(Duration(seconds: 3), () {
      if (Navigator.canPop(context)) {
        Navigator.pop(context);
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('加载完成')));
      }
    });
  }
}

// 使用示例
void main() {
  runApp(MaterialApp(home: DialogDemo(), debugShowCheckedModeBanner: false));
}
